<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Jobs\AttachIpAddressJob;
use App\Jobs\CalculateFollowsNumJob;
use App\Jobs\CalculateLikesNumJob;
use App\Jobs\Posts\UpdatePostOnlyTextJob;
use App\Jobs\Posts\UpdatePostVideoIdJob;
use App\Jobs\Used\UpdateUsedPosterGlassJob;
use App\Lib\WeApp\WeApp;
use App\Models\Used\WxUsedClassify;
use App\Models\Used\WxUsedComment;
use App\Models\Used\WxUsedGood;
use App\Models\Used\WxUsedNeed;
use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UsedController extends BaseController
{

    public function process(Request $request){
        $type = _empty_default_($request->type, '');
        if ($type == 'good_poster') {
            return $this->good_poster($request);
        }
    }

    private function good_poster(Request &$request){
        $uid = _empty_default_($request->uid, 0);
        $used_good_id = _empty_default_($request->used_good_id, 0);
        global $__MINI_GLOBAL_DEVICE__;

        if(_empty_($used_good_id)){
            return $this->fail(200001);
        }

        $used_good = WxUsedGood::find($used_good_id);
        if(_empty_($used_good)){
            return $this->fail(200003);
        }

        if($used_good->image_urls){
            $used_good->pic = _array_key($used_good->image_urls[0], 'url', '');

            $used_good->pic_width = _array_key($used_good->image_urls[0], 'width', '');
            $used_good->pic_height = _array_key($used_good->image_urls[0], 'height', '');


            if($used_good->pic_width >= 0){
                $old_widht = $used_good->pic_width;
                $used_good->pic_width = 363;
                $used_good->pic_height = (int)( (363 * $used_good->pic_height) / $old_widht );
            }
        }

        if(_empty_($used_good->pic)){
            if($used_good->video_cover){
                $used_good->pic = $used_good->video_cover;
            }else{
                $used_good->pic = Settings::get('img_share_default', '');
            }
        }

        $data = [];
        $data['title'] = Settings::get('about_title', '');

        $used_user_id = $used_good->user_id;
        $post_title = $used_good->title;

        // ['glass'=>'', 'theme'=>'black/white', 'attach_id'=>id]
        $poster_glass = get_used_meta($used_good->id, 'used_poster_glass_obj', 'j');
        if(_empty_($poster_glass)){
            $attach_id = FileUtils::get_url_attach_id($used_good->pic);
            if($attach_id){
                $used_poster_glass_obj = [
                    'glass' => '',
                    'theme' => '',
                    'attach_id' => $attach_id
                ];
                $first_glasses = $used_good->pic . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                $path = ImageUtils::upload_url_img($first_glasses);
                if($path && $path['url']){
                    // 二次上传
                    $path2 = ImageUtils::upload_url_img($path['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                    if($path2 && $path2['url']){
                        // 三次上传
                        $path3 = ImageUtils::upload_url_img($path2['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                        if($path3 && $path3['url']){

                            // 四次上传
                            $path4 = ImageUtils::upload_url_img($path3['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                            if($path4 && $path4['url']){
                                $used_poster_glass_obj['glass'] = $path4['url'];
                                update_used_meta($used_good->id, 'used_poster_glass_obj', $used_poster_glass_obj, 'j');
                                FileUtils::force_del_url_file($path3['url']);
                                $data['glass'] = $path4['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                            }else{
                                $used_poster_glass_obj['glass'] = $path3['url'];
                                update_used_meta($used_good->id, 'used_poster_glass_obj', $used_poster_glass_obj, 'j');
                                $data['glass'] = $path3['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                            }

                        }else{
                            $used_poster_glass_obj['glass'] = $path2['url'];
                            update_used_meta($used_good->id, 'used_poster_glass_obj', $used_poster_glass_obj, 'j');
                            $data['glass'] = $path2['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                        }

                    }else{
                        $used_poster_glass_obj['glass'] = $path['url'];
                        update_used_meta($used_good->id, 'used_poster_glass_obj', $used_poster_glass_obj, 'j');
                        $data['glass'] = $path['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                    }
                }else{
                    $data['glass'] = $used_good->pic . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                }
                UpdateUsedPosterGlassJob::dispatch($used_good->id);
            }
        }else{
            if(FileUtils::get_url_attach_id($used_good->pic) == $poster_glass['attach_id']){
                _logger_(__file__, __line__, $poster_glass['theme']);
                if(_empty_($poster_glass['theme'])){
                    UpdateUsedPosterGlassJob::dispatch($used_good->id);
                }
                $data['glass'] = $poster_glass['glass'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
            }else{
                update_used_meta($used_good->id, 'used_poster_glass_obj', null, 'j');
                FileUtils::force_del_url_file($poster_glass['glass']);
            }
        }


        $user = WxUser::where('id', $used_user_id)->first(FieldUtils::userInfoColums());
        if($user){

        }else{
            $user = ['user_name'=>'未知用户'];
        }
        $data['user'] = $user;

        if(empty($used_good->pic)){
            return $this->fail(200006, [], '请先配置“默认分享图片”');
        }

        $page = 'pagesU/used-mall/detail/index';
        $code_url = Utils::getMiniCode($page, 'id='.$used_good->id, $uid);
        $data['qrcode'] = $code_url;
        $data['img'] = $used_good->pic.'?imageMogr2/quality/100/interlace/0/crop/630x800/gravity/center/thumbnail/x800';
        $data['content'] = $post_title;
        $data['tip'] =  Settings::get('app_post_poster_bottom_tip', '❤ 扫一扫，找到你想要的生活');

        if($poster_glass){
            $data['tip_color'] = _array_key($poster_glass, 'theme', 'black') == 'white' ? '#333' : '#FFF';
        }else{
            $data['tip_color'] = '#FFF';
        }

        if($used_good->classify_id > 0){
            $circle_tip = WxUsedClassify::where('id', $used_good->classify_id)->value('name');
        }else{
            $circle_tip = '广场';
        }

        $data['poster2'] = [
            'content' => $post_title,
            'contentImg' => ($used_good->pic == Settings::get('img_post_poster_default', '')) ? '' : ($used_good->pic. '?imageMogr2/quality/100/interlace/0/crop/630x800/gravity/center/thumbnail/x800'),
            'avatar' => $user->user_avatar,
            'locationText' => $circle_tip,
            'locationImg' => env('APP_URL') . '/statics/images/playbill/post/ring.png',
            'userName' => $user->user_name,
            'code' => $code_url,
            'textImg' => env('APP_URL') . '/statics/images/playbill/post/poster-text.png'
        ];
        if(Settings::get('app_h5_home', '')){
            $data['url'] = Settings::get('app_h5_home', '').'/#/pagesU/used-mall/detail/index?id='.$used_good->id;
        }else{
            $data['url'] = env('APP_URL');
        }

        $social = [];
        $share_types = Settings::get('app_post_poster_share_types', []);
        foreach (['wechat', 'timeline', 'qq', 'qzone', 'weibo', 'save'] as $key){
            if(!in_array($key, $share_types)){
                continue;
            }
            if($key == 'wechat'){
                $social[] = [
                    'action' => 'wechat',
                    'color' => '#57be6a',
                    'text' => '微信好友',
                    'icon' => 'mini-icon mini-weixin',
                    'share' => json_encode([
                        'provider' => 'weixin',
                        'type' => 2,
                        'title' => $data['content'],
                        'scene' => 'WXSceneSession',
                        'href' => $data['url'],
                        'imageUrl' => $data['img'],
                        'miniProgram' => [
                            'id' => Settings::get('app_meta_appid',  ''),
                            'path' => '/pagesU/used-mall/detail?id=' . $used_good->id,
                            'type' => 0,
                            'webUrl' => $data['url']
                        ]
                    ]),

                ];
            }else if($key == 'timeline'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    $social[] = [
                        'action' => 'timeline',
                        'color' => '#80cc46',
                        'text' => '朋友圈',
                        'icon' => 'mini-icon mini-pengyouquan1',
                        'share' => json_encode([
                            'provider' => 'weixin',
                            'type' => 2,
                            'title' => $data['content'],
                            'scene' => 'WXSceneTimeline',
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])
                    ];
                }

            }else if($key == 'qq'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'qq',
                        'color' => '#54b4ef',
                        'text' => 'QQ好友',
                        'icon' => 'mini-icon mini-qq1',
                        'share' => json_encode([
                            'provider' => 'qq',
                            'type' => 2,
                            'title' => $data['content'],
                            'summary' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'qzone'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'qzone',
                        'color' => '#f7cf46',
                        'text' => 'QQ空间',
                        'icon' => 'mini-icon mini-Rrl_s_112',
                        'share' => json_encode([
                            'provider' => 'qq',
                            'type' => 1,
                            'title' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'weibo'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'weibo',
                        'color' => '#d4382a',
                        'text' => '微博',
                        'icon' => 'mini-icon mini-weibo',
                        'share' => json_encode([
                            'provider' => 'sinaweibo',
                            'type' => 0,
                            'title' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'save'){
                $social[] = [
                    'action' => 'save',
                    'color' => '#999999',
                    'text' => '保存到相册',
                    'icon' => 'mini-icon mini-xiazai2',
                ];
            }
        }
        $data['social'] = $social;
        if($code_url){
            return $this->success($data);
        }else{
            return $this->fail(300001, $data);
        }
    }

    public function need(Request $request){
        $used_good_id = _empty_default_($request->used_good_id, 0);
        $status = _empty_default_($request->status, 0);
        $uid = $request->uid;

        if(!in_array($status, [0, 1])){
            return $this->fail(200004);
        }

        $user_good = WxUsedGood::find($used_good_id);
        if($user_good){

        }else{
            return $this->fail(200004);
        }

        $model = WxUsedNeed::where('user_id', $uid)->where('used_good_id', $used_good_id)->first();
        if($model){
            if($status == 1){
                if($model->status === 0){
                    $model->status = 1;
                    $model->save();

                    $last_chat = WxChat::where('user_id', $user_good->user_id)->where('object_id', $uid)->orderByDesc('id')->first();
                    if($last_chat && $last_chat->expand_type == 5 && $last_chat->expand_id == $user_good->id){

                    }else{
                        WxContRepositories::add($user_good->user_id, $uid, '', '', '', 0, 0, 0, 0, 0, $user_good->id);
                    }
                }
            }else{
                if($model->status === 1){
                    $model->status = 0;
                    $model->save();
                }
            }

        }else{
            $new_model = new WxUsedNeed();
            $new_model->user_id = $uid;
            $new_model->used_good_id = $used_good_id;
            $new_model->status = $status;
            $new_model->save();

            $last_chat = WxChat::where('user_id', $user_good->user_id)->where('object_id', $uid)->orderByDesc('id')->first();
            if($last_chat && $last_chat->expand_type == 5 && $last_chat->expand_id == $user_good->id){

            }else{
                WxContRepositories::add($user_good->user_id, $uid, '', '', '', 0, 0, 0, 0, 0, $user_good->id);
            }
        }
        return $this->success();
    }


    public function classify_list(Request $request){
        $data = WxUsedClassify::orderBy('order', 'desc')->orderBy('id', 'desc')->where('status', 1)->get();
        if($data && $data->isNotEmpty()){
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    public function list(Request $request){

        global $__MINI_GLOBAL_SCENE__;
        $uid = $request->uid;
        $keyword = $request->keyword;
        $user_id = _empty_default_($request->user_id, 0);
        $status = _empty_default_($request->status, []);
        $orderBy = _empty_default_($request->orderBy, 'id');
        $order = _empty_default_($request->order, 'desc');
        $classify_id = _empty_default_($request->classify_id, 0);
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);
        $minprice = _between_(_empty_default_($request->minPrice, 0), 0, 999999999);
        $maxPrice = _between_(_empty_default_($request->maxPrice, 999999999), 0, 999999999);
        global $__MINI_GLOBAL_TENANT_ID__;

        if($minprice > $maxPrice){
            return $this->fail(200004);
        }

        if(!in_array($orderBy, ['id', 'distance', 'price', 'created_at', 'state'])){
            return $this->fail(200004);
        }
        if(!in_array($order, ['desc', 'asc'])){
            return $this->fail(200004);
        }
        if($orderBy != 'price'){
            $order = 'desc';
        }
        if(is_string($status)){
            $status = explode(',', $status);
        }
        if(_empty_($status)){
            $status = [1];
        }
        if($__MINI_GLOBAL_SCENE__ == 120 && (_empty_($user_id) || $user_id == $uid)){
            $status = [0,1,2,3,4,5,6,7, 99];
        }
        if($orderBy != 'distance'){

            $query = WxUsedGood::whereIn('status', $status);

            if($keyword){
                $query = $query->where(function ($query_) use ($keyword) {
                    $query_->orWhere('title', 'like', '%' . $keyword . '%')
                        ->orWhere('detail', 'like', '%' . $keyword . '%');
                });
            }


            if($minprice > 0){
                $query = $query->where('price', '>=', $minprice);
            }
            if($maxPrice != 9999999999){
                $query = $query->where('price', '<=', $maxPrice);
            }

            if($user_id > 0){
                $query = $query->where('user_id', $user_id);
            }else{
                if($__MINI_GLOBAL_SCENE__ == 120){
                    $query = $query->where('user_id', $uid);
                }
            }

            if($classify_id > 0){
                $query = $query->where('classify_id', $classify_id);
            }

            if($orderBy == 'state'){
                $data = $query->orderBy(DB::raw('FIND_IN_SET(status, "' . implode(",", [1,3,5,6,7,8,9,10]) . '"' . ")"))->orderByDesc('id')
                    ->paginate($limit);
            }else{
                $data = $query->orderBy(DB::raw('FIND_IN_SET(status, "' . implode(",", [1,3,5,6,7,8,9,10]) . '"' . ")"))->orderBy($orderBy, $order)
                    ->paginate($limit);
            }


//            if($classify_id > 0){
//                $query = $query->where('classify_id', $classify_id);
//            }else{
//                $query = $query->whereNotIn('classify_id', $ban_ids);
//            }

            if($data){
                $data->map(function ($v, $k){
                    ShopUtils::used_process($v);
                    return $v;
                });
                return $this->success($data);
            }
            return $this->fail(200003);
        }else{
            if($uid > 0){
                $user_ip = WxUser::where('id', $uid)->value('ip');
                global $__MINI_GLOBAL_IP__;
                if($user_ip != $__MINI_GLOBAL_IP__){
                    WxUser::where('id', $uid)->update([
                        'ip' =>  $__MINI_GLOBAL_IP__
                    ]);
                    AttachIpAddressJob::dispatch(2, $uid)->delay(2);
                }
                $user = WxUser::find($uid);
                $longitude = $user->longitude;
                $latitude = $user->latitude;

                if(_empty_($longitude) && _empty_($latitude)){
                    $res = _ip_address($__MINI_GLOBAL_IP__);
                    if(_empty_($res)){
                        return $this->fail(503003);
                    }
                    $longitude = $res['longitude'];
                    $latitude = $res['latitude'];
                }

                $the_base_id = Cache::remember('used:goods:new:500', 3600 * 5, function (){
                    $base_id = WxUsedGood::where('status', 1)->orderBy('id', 'desc')->skip(500)->value('id');
                    return $base_id > 0 ? $base_id : 0;
                });

                $data = WxUsedGood::select(DB::raw('*, ( 6378137 * acos( cos( radians('.$latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( latitude ) ) ) ) AS distance'))
                    ->where('id', '>', $the_base_id)
                    ->where('status', 1)
                    ->where('user_id', '<>', $uid)
                    ->having('distance', '<', 300000)
                    ->inRandomOrder()
                    ->simplePaginate(10);
                if($data){
                    $data->map(function ($v, $k){
                        ShopUtils::used_process($v);
                        return $v;
                    });
                    return $this->success($data);
                }
            }else{
                return $this->fail(200003, [], '没有获取到您的经纬度信息');
            }
        }
    }

    public function detail(Request $request){
        $id = $request->id;
        if(_empty_($id)){
            return $this->fail(200001);
        }

        $user_good = WxUsedGood::where('id', $id)->first();
        if($user_good){
            ShopUtils::used_process($user_good);
            return $this->success($user_good);
        }
        return $this->fail(200003);
    }

    public function comment_process(Request $request){
        $action = _empty_default_($request->action, '');
        $uid = $request->uid;
        if(_empty_($action)){
            return $this->fail(200001);
        }
        if(!in_array($action, ['add', 'delete'])){
            return $this->fail(200004);
        }
        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }

        if($action == 'add'){

            $used_good_id = _empty_default_($request->used_good_id, 0);
            if(_empty_($used_good_id)){
                return $this->fail(200001);
            }

            if(WxUsedGood::where('id', $used_good_id)->value('status') != 1){
                return $this->fail(200000, [], '该闲置商品不是上架中状态');
            }

//            if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', UserUtils::get_cached_user_name($uid) )) != mb_strlen(UserUtils::get_cached_user_name($uid))){
//                return $this->fail(200041);
//            }

            $comment_id = _empty_default_($request->comment_id, 0);
            if(_empty_($comment_id)){
                $comment_id = 0;
            }

            if($comment_id > 0){
                if(!WxUsedComment::where('id', $comment_id)->where('comment_state', 1)->exists()){
                    return $this->fail(200004, [], '该父级评论不存在');
                }
            }


            $comment_agent_id = _empty_default_($request->comment_agent_id, 0);
            if(_empty_($comment_agent_id)){
                $comment_agent_id = 0;
            }
            if($comment_agent_id > 0){
                $comment_agent_name = UserUtils::get_cached_user($comment_agent_id)['user_name'];
            }

            $comment_content = _empty_default_($request->comment_content, '');
            $comment_img_url = _empty_default_($request->comment_img_url, '');

            if(_empty_($comment_content)){
                return $this->fail(200001);
            }

            $comment_content = strip_tags($comment_content);
            if(mb_strlen($comment_content) <= 0 || mb_strlen($comment_content) > 240){
                return $this->fail(200004, [], '评论内容过长或过短');
            }

            global $__MINI_GLOBAL_IP__;

            // 百度审核
            if(UserUtils::user_permissions_check_by_config($uid, 'audit_used_comment_white_list')){
                $need_manual_review = false;
            }else{
                $need_manual_review = true;
                $is_audit_used_comment = Settings::get('is_audit_used_comment', 0);
                if ($is_audit_used_comment == 2) {
                    $filter_result = BaiduUtils::text_filter($comment_content);
                    if($filter_result){
                        if($filter_result['hit_level'] == 2){
                            // 不合规
                            return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                        }else if($filter_result['hit_level'] == 0){
                            // 审核通过
                            $need_manual_review = false;
                        }
                    }
                }else if($is_audit_used_comment == 0){
                    $need_manual_review = true;
                }else{
                    $need_manual_review = false;
                }
            }

            // 0:审核中，1:审核通过，2:驳回
            $comment_state = 1;
            if($need_manual_review){
                $comment_state = 0;
            }


            $model = new WxUsedComment();
            $model->user_id = $uid;
            $model->used_good_id = $used_good_id;
            if($comment_id > 0){
                $model->comment_id = $comment_id;
            }else{
                $model->comment_id = 0;
            }
            if($comment_agent_id > 0 && $comment_agent_name){
                $model->comment_agent_id = $comment_agent_id;
                $model->comment_agent_name = $comment_agent_name;
            }else{
                $model->comment_agent_id = 0;
            }

            $model->comment_content = $comment_content;
            if(!_empty_($comment_img_url)){
                $model->comment_img_url = $comment_img_url;
            }

            if($__MINI_GLOBAL_IP__){
                $model->ip = $__MINI_GLOBAL_IP__;
            }
            $model->comment_state = $comment_state;
            $r = $model->save();
            if($r){
                return $this->success();
            }
            return $this->fail(200002);
        }else if($action == 'delete'){

        }
    }

    public function comment_list(Request $request){
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);
        $used_good_id = _empty_default_($request->used_good_id, 0);
        if(_empty_($used_good_id)){
            $this->fail(200001);
        }
        $data = WxUsedComment::where('used_good_id', $used_good_id)->where('comment_id', 0)->where('comment_state', 1)->orderBy('id', 'desc')->simplePaginate($limit);
        if($data){
            $data->map(function ($v, $k){
                $v->user = UserUtils::get_cached_user($v->user_id);
                if(_empty_($v->comment_id)){
                    $childData = WxUsedComment::where('comment_id', $v->id)->limit(100)->get();
                    if($childData){
                        $childData->map(function ($v2, $k2){
                            $v2->user = UserUtils::get_cached_user($v2->user_id);
                            $v2->format_time = format_datetime($v2->created_at);
                            return $v2;
                        });
                    }
                    $v->child = $childData;
                }else{
                    $v->child = [];
                }
                $v->format_time = format_datetime($v->created_at);
                return $v;
            });
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    public function status(Request $request){
        $uid = $request->uid;
        $used_id = _empty_default_($request->id, 0);
        $status = _empty_default_($request->status, 0);
        if(_empty_($used_id)){
            return $this->fail(200001);
        }
        if(_empty_($status)){
            $status = 0;
        }
        if(WxUsedGood::where('id', $used_id)->value('user_id') != $uid && !UserUtils::is_mini_admin($uid)){
            return $this->fail(200000);
        }
        // 重新上架，未卖出下架
        if(!in_array($status, [0, 2])){
            return $this->fail(200004);
        }
        // 0：待审核 1: 推送中 2：提前下架 3：交易完成 4：驳回 5: 买家已付款 6:买家已退款
        $old_status = WxUsedGood::where('id', $used_id)->value('status');
        if($status == 2){
            if($old_status != 1){
                return $this->fail(200004, [], '该商品不是推送中状态，无法下线');
            }
        }else if($status === 0){
            if( !in_array($old_status, [2, 6, 4]) ){
                return $this->fail(200004, [], '该商品的状态无法再次上架，请重新发布');
            }
        }

        $r = WxUsedGood::where('id', $used_id)->update([
            'status' => $status
        ]);
        if($r){
            return $this->success(['status' => $status]);
        }
        return $this->fail(200002);
    }

    public function add(Request $request)
    {
        global $__MINI_GLOBAL_PAYCODE_30__,$__MINI_GLOBAL_CURRENT_PLAYER_ID__;
        if(!$__MINI_GLOBAL_PAYCODE_30__){
            return $this->fail(700000);
        }


        $uid = $request->uid;
        $title = _empty_default_($request->title, '');
        $classify_id = _empty_default_($request->classify_id, 0);
        $video_url = _empty_default_($request->video_url, null);
        $video_cover = _empty_default_($request->video_cover, null);
        global $__MINI_GLOBAL_IP__;
        $sync_to_post = _empty_default_($request->add_post, 0) == 1 ? 1 : 0;
        $sync_post_content = _empty_default_($request->post_content, '');
        $sync_post_img = _empty_default_($request->post_img, '');
        $device = $request->header('device','') ?: 'mp';
        if(_empty_($device) || !in_array($device, ['app', 'mp', 'h5', 'pc'])){
            return $this->fail(200001);
        }
        $used_id = _empty_default_($request->id, 0);
        if($used_id > 0){
            $sync_to_post = 0;
            if(WxUsedGood::where('id', $used_id)->value('user_id') != $uid && !UserUtils::is_mini_admin($uid)){
                return $this->fail(200000);
            }
        }

        if($sync_to_post != 1){
            $sync_post_content = '';
            $sync_post_img = '';
        }else{
            if(_empty_($sync_post_content)){
                return $this->fail(200001, '', '同步笔记内容不能为空');
            }
            $sync_post_content = strip_tags($sync_post_content);
        }

//        if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', UserUtils::get_cached_user_name($uid) )) != mb_strlen(UserUtils::get_cached_user_name($uid))){
//            return $this->fail(200041);
//        }

        $user = WxUser::find($uid);
        // 验证资料
        if(Settings::get('used_mall_push_force_bind_phone', 0) == 1){
            if(_empty_($user->phone) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未绑定手机号',
                    'content' => '前往绑定',
                    'confirmText' => '去绑定',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                ], '未绑定手机号');
            }
        }

        if(Settings::get('used_mall_push_force_real_name', 0) == 1){
            if(_empty_($user->real_name) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未实名认证',
                    'content' => '您还没有实名认证，是否前往认证',
                    'confirmText' => '去认证',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/realname/realname'
                ], '未实名认证');
            }
        }

        if(Settings::get('used_mall_push_force_subscribe_mp', 0) == 1){
            if(_empty_($user->weixin_mp_openid) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                $weapp = new WeApp('mp');
                $mpServicer = $weapp->getMpServicer();
                try {
                    $url = $mpServicer->getQrCodeWithPara(0, 'user:bind:'.$user->id);
                }catch (\Exception $e){
                    return $this->fail(200006, [], '生成公众号二维码失败，请检查[全局配置-支付-微信-公众号]');
                }
                if($url){
                    $qrCode = QrCode::format('png')->size(300)->generate($url);
                    $image = Image::make($qrCode);
                    $image->resizeCanvas(300, 300 + 60, 'bottom', false, '#ffffff'); // 增加高度，保持宽高比，背景色为白色
                    $mp_app_name = Settings::get('mp_app_name', '');
                    $text_tip = '关注'.$mp_app_name.'公众号，可以更方便通知到您';
                    if(mb_strlen($mp_app_name) > 4){
                        $text_tip = '关注'.$mp_app_name.'公众号';
                    }
                    $image->text($text_tip, 150, 40, function($font){
                        $font->file(public_path('storage/font/DingTalk_JinBuTi_Regular.ttf')); // 字体文件路径
                        $font->size(13); // 字体大小
                        $font->color('#000000'); // 字体颜色
                        $font->align('center'); // 水平对齐
                        $font->valign('top'); // 垂直对齐
                    });
                    $base64 = 'data:image/png;base64,' . base64_encode($image->encode('png')->getEncoded());
                    return $this->fail(200043, [
                        'title' => '未关注公众号，无法实时获取通知',
                        'content' => '前往关注',
                        'confirmText' => '去关注',
                        'target_type' => 26,
                        'target_id' => $base64
                    ], '未关注公众号');
                }
            }
        }

        if(Settings::get('used_mall_push_force_classify', 0) == 1){
            if(_empty_($classify_id)){
                return $this->fail(200001, [], '请先选择分类');
            }
        }

        if($classify_id > 0){
            if(!WxUsedClassify::where('id', $classify_id)->exists()){
                return $this->fail(200004, [], '所选分类无效');
            }
        }else{
            $classify_id = 0;
        }


        if(_empty_($title)){
            return $this->fail(200001, [], '请填写标题');
        }


        $detail = _empty_default_($request->detail, '');
        if(_empty_($detail)){
            return $this->fail(200001, [], '请填写宝贝介绍');
        }

        $price = _empty_default_($request->price, 0);
        if(_empty_($price)){
            return $this->fail(200001, [], '请填写价格');
        }
        $image_state_change_list = [];

        if(_empty_($video_url)){
            $video_cover = null;
        }


        if(!_empty_($video_url)){
            if(_empty_($video_cover)){
                $res = ImageUtils::upload_video_screenshot($video_url);
                if($res && $res['url']){
                    $video_cover = $res['url'];
                }
            }
        }

        if($video_url){
            $image_state_change_list[] = $video_url;
            if($video_cover){
                $image_state_change_list[] = $video_cover;
            }
        }

        if($sync_post_img){
            $image_state_change_list[] = $sync_post_img;
        }

        $original_price = _empty_default_($request->original_price, 0);

        $is_self_pickup = _empty_default_($request->is_self_pickup, 1);
        if(!in_array($is_self_pickup, [0, 1])){
            return $this->fail(200004);
        }

        $express_cost = 0;
        $is_express_delivery = _empty_default_($request->is_express_delivery, 1);
        if(!in_array($is_express_delivery, [0, 1])){
            return $this->fail(200004);
        }
        if($is_express_delivery){
            $express_cost = _empty_default_($request->express_cost, 0);
            $express_cost = 0;
        }

        $image_urls = _empty_default_($request->image_urls, []);
        if($image_urls && is_string($image_urls)){
            $image_urls = json_decode($image_urls, true);
        }

        if( (_empty_($image_urls) || !is_array($image_urls)) && _empty_($video_url) ){
            return $this->fail(200001, [], '请上传宝贝图片');
        }


        $location = _empty_default_($request->location, []);
        if(_empty_($location)){
            return $this->fail(200001, [], '请选择地址');
        }

        $longitude = _array_key($location, 'longitude', 0);
        $latitude = _array_key($location, 'latitude', 0);
        $address_name = _array_key($location, 'address_name', '');
        $address_detailed = _array_key($location, 'address_detailed', '');

        if(_empty_($longitude) || _empty_($latitude) || _empty_($address_name) || _empty_($address_detailed)){
            return $this->fail(200001, [], '请选择地址');
        }

        $new_imgages = [];
        foreach ($image_urls as $img_obj){
            $img_url = $img_obj['url'];
            $img_info = ImageUtils::get_url_img_info($img_url);
            $obj = [
                'url' => $img_url,
                'width' => 0,
                'height' => 0
            ];
            if($img_info){
                $obj['width'] = $img_info['width'];
                $obj['height'] = $img_info['height'];
            }
            $new_imgages[] = $obj;
            $image_state_change_list[] = $img_url;
        }


        // 百度审核
        if(UserUtils::user_permissions_check_by_config($uid, 'audit_used_good_white_list')){
            $need_manual_review = false;
        }else{
            $need_manual_review = true;
            $is_audit_used_good = Settings::get('is_audit_used_good', 0);
            if ($is_audit_used_good == 2) {
                $filter_result = BaiduUtils::text_filter($title. ' ' . $detail. ' '. $sync_post_content);
                if($filter_result){
                    if($filter_result['hit_level'] == 2){
                        // 不合规
                        return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                    }else if($filter_result['hit_level'] == 0){
                        // 审核通过
                        $need_manual_review = false;
                    }
                }
            }else if($is_audit_used_good == 0){
                $need_manual_review = true;
            }else{
                $need_manual_review = false;
            }
        }
        // 0:审核中，1:审核通过
        $status = 1;
        if($need_manual_review){
            $status = 0;
        }



        DB::beginTransaction();
        try {
            // todo:
            if($used_id > 0){
                $model = WxUsedGood::find($used_id);
            }else{
                $model = new WxUsedGood();
                $model->user_id = $uid;
            }


            $model->title = $title;
            $model->detail = $detail;
            $model->classify_id = $classify_id;

            if($video_url){
                $model->video_url = $video_url;
                $model->video_cover = $video_cover;
            }

            $model->price = $price;
            $model->original_price = $original_price;
            $model->is_self_pickup = $is_self_pickup;
            $model->is_express_delivery = $is_express_delivery;
            $model->express_cost = $express_cost;

            $model->longitude = $longitude;
            $model->latitude = $latitude;
            $model->address_name = $address_name;
            $model->address_detailed = $address_detailed;
            $model->status = $status;

            if($__MINI_GLOBAL_IP__){
                $model->ip = $__MINI_GLOBAL_IP__;
            }

            $model->image_urls = json_encode($new_imgages);
            $r = $model->save();
            if($r){
                if($sync_to_post == 1){
                    $post_id = PostsRepositores::add($uid, 1, '', $sync_post_content, 0, null, null, !_empty_($sync_post_img) ? [['url'=>$sync_post_img]] : [], '', null, null, null, null,
                        null, null, null, null, $device, null, null, null, [$model->id], null);
                    if ($post_id) {
                        CalculateLikesNumJob::dispatch($post_id);
                        UpdatePostVideoIdJob::dispatch($post_id);
                        CalculateFollowsNumJob::dispatch($uid);
                        Redis::sadd('realtime:post:set', $post_id);
                        UpdatePostOnlyTextJob::dispatch(0);
                        UserUtils::add_user_experience($uid, 15, 40);
                    }
                }else{
                    if($status == 1){
                        UserUtils::add_user_experience($uid, 15, 20);
                    }
                }
                if($image_state_change_list){
                    Utils::image_state_change($image_state_change_list, 1);
                }
                if($used_id > 0){
                    Cache::forget('used:near:tenant:'.$used_id);
                }
                if($status === 0){
                    UserUtils::assistant_notice_review(106, $model->id);
                }
                DB::commit();
                return $this->success(['used_good_id' => $model->id]);
            }else{
                DB::rollBack();
                return $this->fail(200002);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }

    }
}
